package com.ssb.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.json.JSONObject;
import com.ssb.po.Order;
import com.ssb.service.OrderService;
import com.ssb.util.GetWxOrderno;


@Controller
public class ResultController {
	@Autowired
	private OrderService orderService;
	@RequestMapping("/notifyServlet")
	public void createOrder(HttpServletRequest request,HttpServletResponse response ){
		System.out.println("进入回调");
		Map< String, String> map=new HashMap<String, String>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		String line = null;
		StringBuilder sb = new StringBuilder();
		try {
			while((line = br.readLine())!=null){
				sb.append(line);
			}
			System.out.println(sb);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			map=GetWxOrderno.doXMLParse(sb.toString());
			if(map.get("return_code").equalsIgnoreCase("success")){
				System.out.println("支付成功");
				Order order=new Order();
				order.setMoney(Integer.valueOf(map.get("total_fee")));
				//处理商家数据包
				String attach=map.get("attach");
				System.out.println(attach);
				JSONObject json=new JSONObject().getObject(attach);
				order.setAdress(json.getString("adress"));
				order.setPhone(json.getString("phone"));
				order.setName(json.getString("name"));
				order.setRemark(json.getString("remark"));
				order.setPaytime(new Date());
				order.setStatus(0);
				orderService.insertSelective(order);
				//返回给微信xml
				String backxml="<xml>"+
						"<return_code><![CDATA[SUCCESS]]></return_code>"+
						"<return_msg><![CDATA[OK]]></return_msg>"+"</xml>";
				response.getWriter().print(backxml);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//sb为微信返回的xml

	}
}